-- Copyright (c) 2025 Huawei Technologies Co., Ltd.
-- openUBMC is licensed under Mulan PSL v2.
-- You can use this software according to the terms and conditions of the Mulan PSL v2.
-- You may obtain a copy of Mulan PSL v2 at: http://license.coscl.org.cn/MulanPSL2
-- THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
-- EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
-- MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
-- See the Mulan PSL v2 for more details.

local class     = require 'mc.class'
local singleton = require 'mc.singleton'
local log       = require 'mc.logging'
local base_msg  = require 'messages.base'
local mctp_lib  = require 'mctp_lib'
local spdm_main = require 'spdm_core'
local spdm_cb   = spdm_main.callbacks

local RET_ERR = -1
local RET_OK  = 0

local MODULE_NAME_SPDM = "SPDM"

local mctp_callbacks = class()

local cbs = spdm_cb.new()
local g_dbus = nil
local g_obj_map = {}

local function get_endpoint(device_name)
    local controller = g_obj_map[device_name]
    if not controller then
        log:error("invalid parameters, cannot get ep")
        error(base_msg.InternalError())
    end
    if controller.endpoint then
        return controller.endpoint
    end

    if not g_dbus then
        log:error("invalid parameters, cannot get ep")
        error(base_msg.InternalError())
    end

    if not controller.phy_addr then
        local phy_addr = mctp_lib.bdf_to_phy_addr(controller.dev.dev_bus, controller.dev.dev_device,
            controller.dev.dev_function)
        log:notice("DevBus: %s, DevDevice: %s, DevFunction: %s", controller.DevBus, controller.DevDevice,
            controller.DevFunction)
        controller.phy_addr = phy_addr
    end

    local ok, endpoint, _ = pcall(mctp_lib.get_endpoint_and_transport, g_dbus, MODULE_NAME_SPDM,
        controller.phy_addr, mctp_lib.MCTP_MSG_TYPE_SPDM)
    if not ok then
        log:error("failed to register mctp transport, return %s", endpoint)
        error(base_msg.InternalError())
    end

    controller.endpoint = endpoint

    return endpoint
end

local function do_mctp_send_recv(device_name, data, _, timeout)
    local endpoint = get_endpoint(device_name)
    -- timeout 是微秒，需要除以1000转换为毫秒
    local rsp = endpoint:Request({}, data, math.floor(timeout / 1000), {}, {})
    return rsp
end

local function mctp_send_recv(...)
    local ok, data = pcall(do_mctp_send_recv, ...)
    if not ok then
        return RET_ERR, ""
    end
    return RET_OK, data
end

function mctp_callbacks.register_dbus(dbus)
    g_dbus = dbus
end

function mctp_callbacks.register_mctp_send_recv_cb(controller)
    g_obj_map[controller.device_name] = controller
    cbs:set_send_recv_cb(controller.device_name, mctp_send_recv)
end

return singleton(mctp_callbacks)
